import json
import scrapy

from ..database.sql import Mysql
from ..items import WeatherItem
from ..models import *


class WeatherSpider(scrapy.Spider):
    name = 'weather'
    allowed_domains = [
        "heweather.com"
    ]
    session = Mysql.get_session()
    session.execute("update city set status=0 where gmt_update < date_format(now(), '%y-%m-%d');")
    session.commit()
    start_urls = []
    base_url = "https://free-api.heweather.com/s6/weather/forecast?location={0}&key=c237270aa304419c959e12c60423f1ec"
    for city in session.query(City).filter(City.province == 'zhejiang').filter(City.status == 0).all():
        start_urls.append(base_url.format(city.id))

    def parse(self, response):
        resp = json.loads(response.body_as_unicode())
        today = resp['HeWeather6'][0]['daily_forecast'][0]
        item = WeatherItem()
        item['weather'] = Weather(
            city_code=response.url.split("location=")[1].split("&")[0],
            tmp_max = today['tmp_max'],
            tmp_min=today['tmp_min'],
            sr=today["sr"],
            ss=today["ss"],
            day_weather=today['cond_txt_d'],
            night_weather=today['cond_txt_n'],
            wind_spd=today['wind_spd'],
            wind_level=today['wind_sc'],
            date=today['date'],
            init_content=today
        )
        yield item
